import { request } from 'umi';


export async function currentUserMenus() {
  return request('/api/getRouters', {
    method: 'GET',
  });
}
export async function getCurrentUserMenus ()  {
  try {
    const routes = await currentUserMenus();
    const menuData = filterMenuData(routes.data);
    return menuData;
  } catch (error) {
    console.log(error);
  }
  return undefined;
};

const filterMenuData = (menuData) => {
  if (!menuData) {
    return [];
  }

  const tempResult = menuData
    .filter((item) => item.name && !item.hideInMenu)
    .map((item) => getSubMenu(item))
    .filter((item) => item);
  const result = tempResult.map((item) => {
    return {
      ...item,
      name: item.meta ? item.meta.title : '',
      icon: item.meta ? item.meta.icon : '',
    };
  });
  return result;
};

const getSubMenu = (item) => {
  if (item.children && !item.hideChildrenInMenu && item.children.some((child) => child.name)) {
    return {
      ...item,
      name: item.meta ? item.meta.title : '',
      icon: item.meta ? item.meta.icon : '',
      children: filterMenuData(item.children), // eslint-disable-line
    };
  }
  return item;
};

export function getMatchMenuItem(path, menuData){
  if(!menuData)
    return [];
  let items= [];
  menuData.forEach((item) => {
    if (item.path) {
      if (item.path === path) {
        items.push(item);
      }
      if (path.length >= item.path?.length) {
        const exp = `${item.path}/*`;
        if (path.match(exp)) {
          if(item.children) {
            const subpath = path.substr(item.path.length+1);
            const subItem = getMatchMenuItem(subpath, item.children);
            items = items.concat(subItem);
          } else {
            const paths = path.split('/');
            if(paths.length >= 2 && paths[0] === item.path && paths[1] === 'index') {
              items.push(item);
            }
          }
        }
      }
    }
  });
  return items;
}

//将TagView中拿到的菜单路由数据（嵌套）变成一个数组
// const { menuData } = routeContext;
export function routeListToArray(menuData,resultArray)
{

  menuData.forEach(item => {

    if(item.routes)
    {

      routeListToArray(item.routes,resultArray)

    }
    else
    {
      resultArray.push(item);
    }

  });

}

export function currentMenuItemToArray(menuItem,resultArray)
{

    resultArray.push(menuItem);
    if(menuItem.routes)
    {
      currentMenuItemToArray(menuItem.routes,resultArray)
    }

}
